<template>
  <div class="address-list-container">
    <div class="address-item" v-for="(item, index) in addressList" :key="index">
      <el-card :style="{ borderColor: selIndex === index ? 'orange' : '#f7f7f7' }">
        <h4 class="address-name">收件人：{{ item.receiveName }}</h4>
        <div class="main">
          <span class="phone">电话：{{ item.receivePhone }}</span>
          <span class="recevie-address">
            地址：{{ item.province + item.area + item.city + item.street }}
          </span>
          <span class="postal-code">邮政编码：{{ item.postalCode }}</span>
        </div>
        
        <div class="edit">
          <el-button size="small" @click="selectAddress(index)">选中</el-button>
          <el-button type="danger" size="small" @click="handleDeleteAddressItem(item.addressId)">删除</el-button>
          <el-button type="info" size="small" @click="handleEditAddressItem(item)">编辑</el-button>
          
        </div>
      </el-card>
    </div>
    <NewAddress style="height: 100%; " />
    <el-dialog v-model="showDialog" title="修改地址">
    <el-form>
      <el-form-item label="姓名">
        <el-input v-model="address.receiveName" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="address.receivePhone" />
      </el-form-item>
      <el-form-item label="地址">
        <el-cascader v-model="selectedRegion" :options="regionData" :props="customProps" filterable
          @change="handleChange" style="width: 100%;"></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input v-model="address.street" type="textarea" placeholder="详细地址，如街道、门牌号、小区、楼栋号、单元室等" />
      </el-form-item>
      <el-form-item label="邮政编码" style="width: 400px;">
        <el-input v-model="address.postalCode" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitAddress">确定</el-button>
    </template>
  </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useAddressStore } from '@/stores/address';
import regionData from '@/data/regionData.json';
import { deleteAddressAPI,updateAddressAPI, getAddressListAPI } from '@/apis/address';
import NewAddress from './NewAddress.vue';
const showDialog = ref(false);
const address = ref({
  receiveName: "",
  receivePhone: "",
  province: "",
  provinceCode: "",
  city: "",
  cityCode: "",
  area: "",
  areaCode: "",
  street: "",
});

const selectedRegion = ref([]);
const customProps = {
  checkStrictly: true,
  expandTrigger: 'hover',
  value: 'code',
  label: 'name',
  children: 'children',
};

const addressList = ref([])
const addressStore = useAddressStore();

const selIndex = ref(-1);
const selectAddress = (index) => {
  // console.log(index);
  selIndex.value = index;
  addressStore.setCurIndex(index);
}

const handleDeleteAddressItem = async (id) => {
  await deleteAddressAPI(id).then(res => {
    if (res.success === true) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      refreshAddressList();
    }else{
      ElMessage({
        message: '删除失败',
        type: 'error',
      })
    }
  })
}

const handleEditAddressItem = (item) => {
  // 创建原始地址对象的深拷贝，以避免直接修改原始数据
  const newItem = JSON.parse(JSON.stringify(item));
  showDialog.value = true;
  address.value = newItem;
  selectedRegion.value = [newItem.provinceCode, newItem.cityCode, newItem.areaCode];
}

const submitAddress = async () => {
  showDialog.value = false;
  updateAddressAPI(address.value.addressId,address.value).then(res => {
    if (res.success === true) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      refreshAddressList();
    }else{
      ElMessage({
        message: '修改失败',
        type: 'error',
      })
    }
  })
}

function findRegionItem(code, data = regionData, level = 0) {
  if (level === 0) return data.find(item => item.code === code);
  for (const item of data) {
    if (item.children) {
      const found = findRegionItem(code, item.children, level - 1);
      if (found) return found;
    }
  }
  return null;
}

function handleChange() {
  const codes = selectedRegion.value;

  if (codes.length >= 1) {
    const province = findRegionItem(codes[0]);
    if (province) {
      address.value.province = province.name;
      address.value.provinceCode = province.code;
    }
  }
  if (codes.length >= 2) {
    const city = findRegionItem(codes[1], regionData.find(r => r.code === codes[0])?.children);
    if (city) {
      address.value.city = city.name;
      address.value.cityCode = city.code;
    }
  }
  if (codes.length === 3) {
    const area = findRegionItem(codes[2], regionData.find(r => r.code === codes[0])?.children.find(c => c.code === codes[1])?.children);
    if (area) {
      address.value.area = area.name;
      address.value.areaCode = area.code;
    }
  }
}


// 刷新地址列表
const refreshAddressList = async () => {
  await getAddressListAPI().then(res => {
    console.log(res);
    addressStore.setAddressList(res.data.records)
    addressList.value = addressStore.getAddressList()
  })
  
}


onMounted(() => {
  refreshAddressList();
})
</script>

<style lang="scss" scoped>
.address-list-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
  .edit {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }

  .address-item {
    width: 23rem;
    background: #f7f7f7;
    border-radius: 4px;
    padding: 20px;

  }

  .address-add {
    width: 20rem;
    background: #f7f7f7;
    border-radius: 4px;
    padding: 20px;
    cursor: pointer;

    .el-card {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #827e0e;

      .el-icon {
        margin-left: 20px;
        font-size: 24px;
      }

      p {
        margin-top: 10px;
      }

      &:hover {
        background: #f0f0f0;
        color: #000;
      }

    }

  }

  h3 {
    margin-bottom: 20px;
  }

  .el-card {
    margin-bottom: 20px;

    .el-card__body {
      padding: 20px;
    }
  }
}

.address-name {
  font-weight: bold;
  margin-bottom: 10px;
}

.main {
  justify-content: space-between;

  .phone {
    margin-right: 10px;
    display: inline-block;
    width: 100%;
  }

  .recevie-address {
    margin-bottom: 10px;
    width: 100%;

  }

.postal-code{
  margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
}



.el-button {
  margin-left: 5px;
}

@media screen and (max-width: 768px) {
  .address-item {
    width: 100%;
  }
}
</style>